import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/route_manager.dart';
import 'package:my_app/components/goods_detail/index.dart';
import 'package:my_app/custom_swiper/index.dart';
import 'package:my_app/mock/goods_category.dart';
import 'package:my_app/mock/goods_list.dart';
import 'package:my_app/pages/toolbar/menu/goods_list_row.dart';
import 'package:my_app/pages/toolbar/menu/widgets/classify_desc.dart';
// import 'package:my_app/uitls/global.dart';

class Menu extends StatefulWidget {
  static _MenuState? _menuState;

  getAppBar() => _menuState?.createAppBar();

  Menu() {
    _menuState = _MenuState();
  }

  @override
  State<Menu> createState() => _MenuState();
}

class _MenuState extends State<Menu> {
  static int? nowCategoryId;
  static double _nestScrollOffset = 0;

  final ScrollController _nestedScrollController = ScrollController();
  final ScrollController _goodsListController = ScrollController();
  final List<double> _categoryPositions = [];

  Map<String, dynamic> categoryCombineGoods = {};

  final List actives = ['满50减20', '充2赠1', '买2送1'];

  List<Widget> goodsListWidgets = [];
  List<MockGoodsCategory> category = MockGoodsCategory.data();

  AppBar? createAppBar() {
    return null;
  }

  @override
  void initState() {
    _nestedScrollController.addListener(() {
      setState(() {
        _nestScrollOffset = _nestedScrollController.offset;
      });
    });

    Future.delayed(Duration.zero, () async {
      if (mounted) {
        _init(context);
      }
    });
    super.initState();
  }

  void _scrollToCategory(int categoryId) {
    if (categoryId < _categoryPositions.length) {
      _goodsListController.animateTo(
        _categoryPositions[categoryId],
        duration: Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  _init(BuildContext context) async {
    List<MockGoods> goods = MockGoods.data();
    List<Widget> goodsListWidgetsTemp = [];
    Random rand = Random();
    double currentPosition = 0.0;

    for (var item in category) {
      var categoryId = category.indexOf(item);
      
      // 记录分类标题的位置
      _categoryPositions.add(currentPosition);
      
      // 分类标题
      goodsListWidgetsTemp.add(ClassifyDesc(item.name, desc: item.desc));
      currentPosition += 51.0; // 分类标题的估计高度

      // 获取当前分类的所有商品
      var categoryGoods = goods.where((g) => g.categoryId == categoryId).toList();
      
      // 每个商品单独一行显示
      for (var goodsItem in categoryGoods) {
        var goodsId = goods.indexOf(goodsItem);
        goodsListWidgetsTemp.add(
          Container(
            margin: EdgeInsets.only(bottom: 10),
            child: GoodsListRow(
              onPress: (BuildContext context) {
                showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (BuildContext context) {
                    return GoodsDetailDialog(
                      id: goodsId,
                    );
                  },
                );
              },
              data: goodsItem,
              border: true,
              activeDesc: actives[rand.nextInt(3)],
            ),
          ),
        );
        currentPosition += 104.0; // 商品行的估计高度
      }
    }

    setState(() {
      nowCategoryId = 0;
      goodsListWidgets = goodsListWidgetsTemp;
      category = MockGoodsCategory.data();
    });
  }

  @override
  Widget build(BuildContext context) {
    return NestedScrollView(
      controller: _nestedScrollController,
      headerSliverBuilder: (context, innerBoxIsScrolled) {
        return [
          SliverAppBar(
            expandedHeight: 186,
            pinned: true,
            floating: false,
            elevation: 0,
            title: Text(
              'select coffe or food',
              style: TextStyle(
                color: Color.fromRGBO(56, 56, 56, 1),
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            backgroundColor: Colors.white,
            flexibleSpace: FlexibleSpaceBar(
              background: SafeArea(
                child: Container(
                  margin: EdgeInsets.only(top: 56),
                  child: InkWell(
                    child: Opacity(
                      opacity: 1,
                      child: CustomSwiper([
                        'lib/assets/images/menu/swiper1.jpg',
                        'lib/assets/images/menu/swiper2.png',
                      ], height: 130),
                    ),
                    onTap: () {},
                  ),
                ),
              ),
            ),
          ),
        ];
      },
      body: Container(
        padding: EdgeInsets.only(top: _nestScrollOffset >= 130 ? (_nestScrollOffset - 130) : 0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
              width: 90,
              color: Color.fromRGBO(248, 248, 248, 1),
              child: Column(
                children: category.map((item) {
                  var index = category.indexOf(item);
                  return InkWell(
                    onTap: () {
                      setState(() {
                        nowCategoryId = index;
                      });
                      _scrollToCategory(index);
                    },
                    child: Container(
                      alignment: Alignment.center,
                      height: 44,
                      decoration: BoxDecoration(
                        border: Border(
                          bottom: BorderSide(
                            color: nowCategoryId == index
                            ? Color.fromRGBO(242, 242, 242, 1)
                            : Colors.transparent,
                          )
                        ),
                        color: Color(0xffffffff).withAlpha(nowCategoryId == index ? 255 : 0),
                      ),
                      child: Text(item.name),
                    ),
                  );
                }).toList(),
              ),
            ),

            Container(
              width: Get.width - 90,
              padding: EdgeInsets.symmetric(horizontal: 14),
              child: NotificationListener(
                child: ScrollConfiguration(
                  behavior: ScrollConfiguration.of(context).copyWith(
                    scrollbars: false,
                  ),
                  child: ListView(
                    controller: _goodsListController,
                    physics: const ClampingScrollPhysics(),
                    padding: EdgeInsets.zero,
                    children: goodsListWidgets,
                  ),
                ),
                onNotification: (ScrollNotification scrollInfo) {
                  return false;
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
